package com.shunda.ysdgj.manager.interceptor;

import com.shunda.ysdgj.common.exception.CustomException;
import com.shunda.ysdgj.model.enums.TimeEnum;
import com.shunda.ysdgj.model.vo.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            throw new CustomException(ResultCodeEnum.LOGIN_EXPIRED);
        }
        String sysUserJsonStr = redisTemplate.opsForValue().get(token);
        if (sysUserJsonStr == null) {
            throw new CustomException(ResultCodeEnum.LOGIN_EXPIRED);
        }
        Long expireTime = redisTemplate.getExpire(token, TimeUnit.MINUTES);
        if (expireTime != null) {
            redisTemplate.expire(token, expireTime + TimeEnum.ADMIN_LOGIN_RENEW_MINUTES.getTime(), TimeUnit.MINUTES);
        }
        return true;
    }
}
